package com.milo.coding.jmm;

/**
 * @Author milo
 * @Date 2021-01-18 17:41:19
 * @description: 原子性
 **/
public class Jmm04_CodeAtomic {

    // volatile 不保证原子性
    // private volatile static int counter = 0;
    private static int counter = 0;

    static Object object = new Object();

    public static void main(String[] args) {

        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(()->{
                for (int j = 0; j < 1000; j++) {
                    synchronized (object){ // 保证原子性
                        counter++;//分三步- 读，自加，写回
                        //读
                    }
                }
            });
            thread.start();
        }

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(counter);

    }
}
